<!-- 车辆保养 -->
<template>
  <div class="page-container">
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
    <table-index :table="table" @loadData="loadData">
      <template #bindOrder="{ record }">
        <div v-if="record.orderNo">
          <a-link type="link" @click="() => onLink(record)">{{ record.orderNo }}</a-link>
          <div>交车人：{{ record.giveStaffName || '-' }}</div>
        </div>
        <span v-else>-</span>
      </template>
      <template #maintenanceAmount="{ record }">
        <span>{{ record.maintenanceAmount ? record.maintenanceAmount : '-' }}</span>
      </template>
      <template #memberInfo="{ record }">
        <memberInfo :record="record" />
      </template>
    </table-index>
  </div>
  <!-- 导入 -->
  <import-modal ref="imoportRef" action="/carMaintenance/importExcel" download-import="carMaintenance" @ok="loadData" />
</template>

<script setup name="CarMaintenanceList">
  import { getMaintenanceList, getStoreList, MaintenanceExportExcel, carMaintenanceClose } from '@/api/asset/maintenance'
  import { useExport } from '@/hooks/list'
  import { onMounted, ref, reactive, computed } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import useNavigate from '@/hooks/useNavigate'
  import memberInfo from '@/views/assets/compnoents/memberInfo.vue'
  import dayjs from 'dayjs'
  import { Modal, Notification } from '@arco-design/web-vue'
  import { usePageDict } from '@/hooks/useDict'

  const { navigateTo } = useNavigate()
  const imoportRef = ref(null)
  const operationDict = usePageDict('operationDict')
  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '车牌号', prop: 'licenseNo', type: 'a-input' },
      {
        label: '车辆当前归属门店',
        prop: 'carSiteIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_site_listBystaff',
        },
      },
      {
        label: '保养状态',
        prop: 'statusList',
        type: 'a-select',
        multiple: true,
        options: operationDict.maintenanceStatusEnum,
      },
      {
        label: '下一次保养日期',
        prop: 'nextMaintenanceDate',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.estimatedTimeS = value[0]
          queryParam.estimatedTimeE = value[1]
        },
      },
      {
        label: '保养单关联门店',
        prop: 'siteIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_site_listBystaff',
        },
      },
      {
        label: '入厂日期',
        prop: 'inDateDate',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.inDateStart = value[0]
          queryParam.inDateEnd = value[1]
        },
      },
      {
        label: '出厂日期',
        prop: 'onDateDate',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.onDateStart = value[0]
          queryParam.onDateEnd = value[1]
        },
      },
      { label: '保养单号', prop: 'maintenanceNo', type: 'a-input' },
      {
        label: '负责人',
        prop: 'undertakerIdList',
        type: 'remote-select',
        attrs: {
          type: 'staff_authOrg_multiple',
        },
      },
      { label: '车架号', prop: 'carVin', type: 'a-input' },
      {
        label: '修理厂',
        prop: 'maintenanceShopId',
        type: 'remote-select',
        attrs: {
          type: 'supplier_list',
          params: {
            status: 1,
            supplierType: 1,
          },
        },
      },
      { label: '关联单号', prop: 'orderNoLike', type: 'a-input', maxlength: 100 },
    ]
  })
  // 接口参数（不包含page信息）
  const queryParam = reactive({
    searchDate: [],
    nextMaintenanceDate: [],
  })

  // table 配置
  const table = useTable({
    queryParam,
    columns: [
      { title: '保养单号', dataIndex: 'maintenanceNo', width: 150, fixed: 'left' },
      { title: '车牌号', dataIndex: 'licenseNo' },
      { title: '车辆当前归属门店', dataIndex: 'carSiteName', width: 150 },
      { title: '保养单关联门店', dataIndex: 'siteName', width: 150 },
      { title: '修理厂', dataIndex: 'maintenanceShop' },
      {
        title: '入厂时间',
        dataIndex: 'entranceDate',
        width: 170,
        sortable: {
          sorter: true,
          sortDirections: ['ascend', 'descend'],
        },
        render: (record) => {
          if (record.entranceDate) {
            return dayjs(record.entranceDate).format('YYYY-MM-DD HH:mm:ss')
          }
        },
      },
      {
        title: '出厂时间',
        dataIndex: 'exportDate',
        width: 170,
        sortable: {
          sorter: true,
          sortDirections: ['ascend', 'descend'],
        },
        render: (record) => {
          if (record.exportDate) {
            return dayjs(record.exportDate).format('YYYY-MM-DD HH:mm:ss')
          }
        },
      },
      { title: '上一次保养里程', dataIndex: 'lastTimeKilometre', unit: '公里', width: 170 },
      { title: '本次保养里程', dataIndex: 'entranceKilometre', unit: '公里', width: 170 },
      { title: '下一次保养时间', dataIndex: 'estimatedTime', width: 170 },
      { title: '下一次保养里程', dataIndex: 'estimatedKilometre', unit: '公里', width: 170 },
      { title: '关联单号', dataIndex: 'order', slotName: 'bindOrder', width: 240 },
      { title: '承租人信息', dataIndex: 'memberInfo', slotName: 'memberInfo', width: 120 },
      { title: '费用金额', dataIndex: 'maintenanceAmount', slotName: 'maintenanceAmount', unit: '元', width: 120 },
      { title: '保养状态', dataIndex: 'statusStr', width: 100 },
      { title: '负责人', dataIndex: 'undertaker', width: 120 },
    ],
    operates: [
      {
        label: '详情', //展示保养计划内容
        permission: 'svms:asstes:car:car-maintenance.detail',
        method: (record, column, rowIndex) => {
          console.log(record, column, rowIndex)
          navigateTo(`/car-maintenance/detail/${record.id}?status=${record.status}`, `${record.licenseNo}-保养详情`)
        },
      },
      {
        label: '编辑',
        permission: 'svms:asstes:car:car-maintenance.edit',
        show: (record) => record.status == 0 || record.status == 1 || record.status == 2,
        method: (record) => {
          // 0 待保养 1 保养中 2 保养完成 7 已关闭
          if (record.status == 2) {
            navigateTo(`/car-maintenance/end/${record.id + '&finish'}?page=carMaintenance`, `${record.licenseNo}-保养编辑`)
          } else if (record.status == 1) {
            navigateTo(`/car-maintenance/start/${record.id + '&start'}?page=carMaintenance`, `${record.licenseNo}-保养编辑`)
          } else {
            navigateTo(`/car-maintenance/edit/${record.id}?page=carMaintenance`, `${record.licenseNo}-保养编辑`)
          }
        },
      },
      {
        label: '开始保养',
        permission: 'svms:asstes:car:car-maintenance.start',
        show: (record) => record.status == 0,
        method: (record) => {
          navigateTo(`/car-maintenance/start/${record.id + '&start'}?page=carMaintenance`, `${record.licenseNo}-开始保养`)
        },
      },
      {
        label: '完成保养',
        permission: 'svms:asstes:car:car-maintenance.end',
        show: (record) => record.status == 1,
        method: (record) => {
          navigateTo(`/car-maintenance/end/${record.id + '&end'}?page=carMaintenance`, `${record.licenseNo}-完成保养`)
        },
      },
      {
        label: '费用信息',
        permission: 'svms:asstes:car:car-maintenance.fee',
        show: (record) => record.status == 2,
        method: (record) => {
          navigateTo(`/car-maintenance/detail/${record.id}?activeType=${2}&status=${record.status}`, `${record.licenseNo}-费用信息`)
        },
      },
      {
        label: '关闭',
        permission: 'svms:asstes:car:car-maintenance.close',
        show: (record) => record.status == 0 || record.status == 1,
        method: (record) => {
          Modal.confirm({
            title: '关闭保单',
            cancelText: '取消',
            okText: '确认',
            bodyStyle: {
              'text-align': 'center',
            },
            content: '关闭后，不支持恢复，是否确认关闭？',
            onOk: () => {
              carMaintenanceClose({ id: record.id }).then(() => {
                Notification.success({
                  content: '关闭成功',
                  closable: true,
                  duration: 3000,
                })
                loadData()
              })
            },
          })
        },
      },
      {
        label: '操作记录',
        permission: 'svms:asstes:car:car-maintenance.operaterecords',
        method: (record) => {
          navigateTo(`/car-maintenance/detail/${record.id}?activeType=${3}&status=${record.status}`, `${record.licenseNo}-操作记录`)
        },
      },
      // 5.3.0版本隐藏 删除
      // {
      //   label: '删除',
      //   permission: 'svms:asstes:car:car-maintenance.delete',
      //   show: (record) => record.status != 1,
      //   method: (record) => {
      //     Modal.confirm({
      //       title: '删除保单',
      //       simple: true,
      //       cancelText: '取消',
      //       okText: '确定',
      //       bodyStyle: {
      //         'text-align': 'center',
      //       },
      //       content: '删除后，不支持恢复，是否确认删除？',
      //       onOk: () => {
      //         carMaintenanceDelete({ id: record.id }).then(() => {
      //           Notification.success({
      //             content: '删除成功',
      //             closable: true,
      //             duration: 3000,
      //           })
      //           loadData()
      //         })
      //       },
      //     })
      //   },
      // },
    ],
    buttons: [
      {
        mode: 'import',
        label: '导入',
        permission: 'svms:asstes:car:car-maintenance.import',
        method: () => {
          imoportRef.value.show()
        },
      },
      {
        mode: 'import',
        label: '导出',
        permission: 'svms:asstes:car:car-maintenance.export',
        method: () => handleExport(),
      },
      {
        type: 'primary',
        permission: 'svms:asstes:car:car-maintenance.add',
        mode: 'import',
        icon: 'plus',
        label: '新增',
        method: () => {
          navigateTo('/car-maintenance/create/create?page=carMaintenance')
        },
      },
    ],
  })
  const onLink = (record) => {
    if (record.orderType == 2) {
      navigateTo(`/short-order/detail/${record.orderId}`, `${record.orderNo}-短租详情`)
    } else if (record.orderType == 3) {
      navigateTo(`/long-order/detail/${record.orderId}`, `${record.orderNo}-长租详情`)
    }
  }
  // 列表接口调用
  const loadData = useFetchTableDataApi(table, queryParam, getMaintenanceList)

  // 导出事件
  const handleExport = () => {
    useExport(MaintenanceExportExcel, queryParam)
  }

  // 门店列表
  const storeList = ref([])
  const getStore = () => {
    getStoreList().then((res) => {
      const result = res.result.map((e) => {
        e.value = e.id
        e.label = e.siteName
        return e
      })
      storeList.value = result
    })
  }

  onMounted(() => {
    loadData()
    getStore()
  })
</script>

<style lang="less" scoped></style>
